const cacheMap = new Map()
// #ifdef H5
import Cookies from 'js-cookie'
// #endif
import { isH5 } from '@/utils/platform'
let timeoutDefault = 1200
const arr = ['ut', 'theme', 'platformId', 'locale']

function isTimeout(name: string) {
  const data = cacheMap.get(name)
  if (!data) return true
  if (data.timeout === 0) return false
  const currentTime = Date.now()
  const overTime = (currentTime - data.createTime) / 1000
  if (overTime > data.timeout) {
    cacheMap.delete(name)
    if (name.startsWith('_')) {
      try {
        uni.removeStorageSync(name)
      } catch (e) {
        console.log(e)
      }
    }
    return true
  }
  return false
}

class CacheCell {
  private data: any
  private timeout: number
  private createTime: number
  constructor(data: any, timeout: number) {
    this.data = data
    this.timeout = timeout
    this.createTime = Date.now()
  }
}

class MinCache {
  constructor(timeout = timeoutDefault) {
    try {
      const res: any = uni.getStorageInfoSync()

      if (isH5) {
        res.keys = [...Object.keys(Cookies.get()), ...res.keys]
      }

      res.keys.forEach((name) => {
        try {
          let value
          if (isH5 && arr.includes(name)) {
            value = Cookies.get(name)
          } else {
            value = uni.getStorageSync(name)
          }

          cacheMap.set(name, value)
        } catch (e) {
          console.log(e)
        }
      })
    } catch (e) {
      console.log(e)
    }
    timeoutDefault = timeout
  }
  set(name: string, data: any, timeout = timeoutDefault) {
    let cache: any = null
    const cachecell = new CacheCell(data, timeout)
    try {
      if (isH5 && arr.includes(name)) {
        Cookies.set(name, data)
      } else {
        uni.setStorageSync(name, cachecell)
      }

      cache = cacheMap.set(name, cachecell)
    } catch (e) {
      console.log(e)
    }
    return cache
  }
  get(name: string) {
    // if (isTimeout(name)) {
    //   return null
    // }

    if (isH5 && arr.includes(name)) {
      return Cookies.get(name)
    } else {
      return cacheMap.get(name)?.data
    }
  }
  delete(name: string) {
    let value = false
    try {
      if (isH5 && arr.includes(name)) {
        Cookies.remove(name)
      } else {
        uni.removeStorageSync(name)
      }

      value = cacheMap.delete(name)
    } catch (e) {
      console.log(e)
    }

    return value
  }
  has(name: string) {
    return !isTimeout(name)
  }
  clear() {
    let value = false
    try {
      if (isH5) {
        Object.keys(Cookies.get()).forEach((item) => {
          Cookies.remove(item)
        })
        uni.clearStorageSync()
      } else {
        uni.clearStorageSync()
      }

      cacheMap.clear()
      value = true
    } catch (e) {
      console.log(e)
    }
    return value
  }
}

export const minCache = new MinCache()
